var pkg = require('./package.json');

var gulp = require('gulp');
var uglify = require('gulp-uglify');// 压缩文件
var minify = require('gulp-minify-css');// 压缩css文件
var concat = require('gulp-concat');// 合并js文件
var rename = require('gulp-rename');// 文件重命名
var replace = require('gulp-replace');// 替换目标文件中的文本
var header = require('gulp-header');// 模板页面插入
var del = require('del');// 删除文件
var gulpif = require('gulp-if');// 条件判断
var minimist = require('minimist');// 解析命令行
var babel = require('gulp-babel');

// JS头部注释
var note = [
    '/** <%= pkg.name %>-v<%= pkg.version %> <%= pkg.license %> License By <%= pkg.homepage %> */\n <%= js %>'
    , {pkg: pkg, js: ';'}
]
// 打包后文件目录
 , destDir = './dist'
// 任务
, task = {

    //压缩 JS
    minjs: function(){
        var dirs = [
            {rule:['./src/controller/*.js'],dir:'/controller'}
            ,{rule:['./src/lib/*.js'],dir:'/lib'}
            ,{rule:['./src/js/captcha/verify.js'],dir:'/js/captcha'}
            ,{rule:['./src/lib/extend/*.js','!./src/lib/extend/Base64.js'],dir:'/lib/extend'}
        ];
        dirs.forEach((o,i)=>{
            console.log(o);
            gulp.src(o.rule) .pipe(babel({
                presets: ['@babel/env']
            })).pipe(uglify())
                .pipe(header.apply(null, note))
                .pipe(gulp.dest(destDir+o.dir));
        });
        return  gulp.src('./src/*.js') .pipe(babel({
            presets: ['@babel/env']
        })).pipe(uglify())
            .pipe(header.apply(null, note))
            .pipe(gulp.dest(destDir));
    },

    //复制文件夹
    mv: function () {
        gulp.src('./src/img/**/*').pipe(gulp.dest(destDir+'/img'));
        gulp.src('./src/json/**/*').pipe(gulp.dest(destDir+'/json'));
        gulp.src('./src/lib/plugin/**').pipe(gulp.dest(destDir+'/lib/plugin'));
        gulp.src(['./src/js/captcha/**','!./src/js/captcha/verify.js']).pipe(gulp.dest(destDir+'/js/captcha'));
        gulp.src('./src/layui/**/*').pipe(gulp.dest(destDir+'/layui'));
        gulp.src('./src/My97DatePicker/**/*').pipe(gulp.dest(destDir+'/My97DatePicker'));
        gulp.src('./src/style/**/*').pipe(gulp.dest(destDir+'/style'));
        gulp.src('./src/template/**/*').pipe(gulp.dest(destDir+'/template'));
        gulp.src('./src/views/**/*').pipe(gulp.dest(destDir + '/views'));
        gulp.src('./src/file/**/*').pipe(gulp.dest(destDir + '/file'));
        gulp.src('./src/*.txt').pipe(gulp.dest(destDir))
        return  gulp.src('./src/*.html').pipe(gulp.dest(destDir));
    }
};

// 清理目标路径文件
gulp.task('clear', function (cb) {
    return del(['./dist/*'], cb);
});
gulp.task('mv', task.mv);
gulp.task('minjs', task.minjs);

gulp.task('default', ['clear'], function () {
    for (var key in task) {
        task[key]();
    }
});